import { v4 as uuidv4 } from 'uuid';
import typedHttp from '@/utils/typedHttp';
import { 
  type RemediationItem, 
  RemediationStatus, 
  type RemediationFormData 
} from '@/types/Remediation';
import { type ComplianceItem, RiskLevel } from '@/types/work';

// 本地存储键前缀
const STORAGE_KEY_PREFIX = 'remediation_items_';

// 最大缓存计划数量
const MAX_CACHED_PLANS = 3;

// 缓存管理
interface CacheMetadata {
  planIds: string[];  // 按最近使用顺序存储的plan_id列表
  lastUpdated: string;
}

/**
 * 获取缓存元数据
 */
const getCacheMetadata = (): CacheMetadata => {
  const metadata = localStorage.getItem('remediation_cache_metadata');
  if (metadata) {
    try {
      return JSON.parse(metadata);
    } catch (error) {
      console.error('Failed to parse remediation cache metadata:', error);
    }
  }
  return { planIds: [], lastUpdated: new Date().toISOString() };
};

/**
 * 更新缓存元数据
 */
const updateCacheMetadata = (metadata: CacheMetadata): void => {
  localStorage.setItem('remediation_cache_metadata', JSON.stringify(metadata));
};

/**
 * 更新最近使用的计划ID
 */
const updateRecentPlanId = (planId: string): void => {
  const metadata = getCacheMetadata();
  
  // 如果已存在，先移除
  const index = metadata.planIds.indexOf(planId);
  if (index !== -1) {
    metadata.planIds.splice(index, 1);
  }
  
  // 添加到列表开头（最近使用）
  metadata.planIds.unshift(planId);
  
  // 如果超过最大缓存数量，移除最旧的
  if (metadata.planIds.length > MAX_CACHED_PLANS) {
    const removedPlanId = metadata.planIds.pop();
    if (removedPlanId) {
      // 清除被移除计划的缓存
      localStorage.removeItem(`${STORAGE_KEY_PREFIX}${removedPlanId}`);
    }
  }
  
  metadata.lastUpdated = new Date().toISOString();
  updateCacheMetadata(metadata);
};

/**
 * 获取特定计划的整改项（先从本地缓存获取，如果没有则从API获取）
 */
export const getRemediationItems = async (planId: string): Promise<RemediationItem[]> => {
  // 先尝试从本地缓存获取
  const storageKey = `${STORAGE_KEY_PREFIX}${planId}`;
  const cachedItems = localStorage.getItem(storageKey);
  
  if (cachedItems) {
    try {
      const items = JSON.parse(cachedItems);
      // 更新最近使用的计划ID
      updateRecentPlanId(planId);
      return items;
    } catch (error) {
      console.error(`Failed to parse cached remediation items for plan ${planId}:`, error);
    }
  }
  
  // 如果缓存中没有，从API获取
  try {
    const backendItems = await typedHttp.get<Record<string, any>[]>(`/remediation/plan/${planId}`);
    
    // 转换为前端格式
    const items = backendItems.map(toFrontendFormat);
    
    // 缓存获取到的数据
    localStorage.setItem(storageKey, JSON.stringify(items));
    
    // 更新最近使用的计划ID
    updateRecentPlanId(planId);
    
    return items;
  } catch (error) {
    console.error(`Failed to fetch remediation items for plan ${planId}:`, error);
    return [];
  }
};

/**
 * 添加整改项
 */
export const addRemediationItem = async (data: RemediationFormData): Promise<RemediationItem | null> => {
  const now = new Date().toISOString();
  const newItem: RemediationItem = {
    id: uuidv4(),
    item_id: data.item_id,
    plan_id: data.plan_id,
    title: data.title,
    description: data.description,
    suggestion: data.suggestion,
    riskLevel: data.riskLevel,
    status: RemediationStatus.IN_PROGRESS,
    updatedAt: now,
  };
  
  try {
    // 转换为后端格式并发送到API
    const backendItem = toBackendFormat(newItem);
    const savedBackendItem = await typedHttp.post<Record<string, any>, Record<string, any>>('/remediation/', backendItem);
    
    // 转换回前端格式
    const savedItem = toFrontendFormat(savedBackendItem);
    
    // 更新本地缓存
    const storageKey = `${STORAGE_KEY_PREFIX}${data.plan_id}`;
    const cachedItems = localStorage.getItem(storageKey);
    
    if (cachedItems) {
      try {
        const items = JSON.parse(cachedItems);
        localStorage.setItem(storageKey, JSON.stringify([...items, savedItem]));
      } catch (error) {
        console.error('Failed to update cached remediation items:', error);
      }
    }
    
    // 更新最近使用的计划ID
    updateRecentPlanId(data.plan_id);
    
    return savedItem;
  } catch (error) {
    console.error('Failed to add remediation item:', error);
    return null;
  }
};

/**
 * 更新整改项
 */
export const updateRemediationItem = async (id: string, updates: Partial<RemediationItem>): Promise<RemediationItem | null> => {
  try {
    // 转换为后端格式并发送到API
    const backendUpdates = toBackendFormat(updates);
    const updatedBackendItem = await typedHttp.put<RemediationItem, Record<string, any>>(`/remediation/${id}`, backendUpdates);
    
    // 转换回前端格式
    const updatedItem = toFrontendFormat(updatedBackendItem);
    
    // 找出plan_id用于缓存更新
    let planId = updates.plan_id;
    if (!planId && 'plan_id' in updatedItem) {
      planId = updatedItem.plan_id;
    }
    
    // 更新本地缓存
    if (planId) {
      const storageKey = `${STORAGE_KEY_PREFIX}${planId}`;
      const cachedItems = localStorage.getItem(storageKey);
      
      if (cachedItems) {
        try {
          const items = JSON.parse(cachedItems);
          const updatedItems = items.map((item: RemediationItem) => 
            item.id === id ? updatedItem : item
          );
          localStorage.setItem(storageKey, JSON.stringify(updatedItems));
        } catch (error) {
          console.error('Failed to update cached remediation items:', error);
        }
      }
      
      // 更新最近使用的计划ID
      updateRecentPlanId(planId);
    }
    
    return updatedItem;
  } catch (error) {
    console.error(`Failed to update remediation item ${id}:`, error);
    return null;
  }
};

/**
 * 删除整改项
 */
export const deleteRemediationItem = async (id: string, planId: string): Promise<boolean> => {
  try {
    // 发送到API
    await typedHttp.delete(`/remediation/${id}`);
    
    // 如果成功，更新本地缓存
    const storageKey = `${STORAGE_KEY_PREFIX}${planId}`;
    const cachedItems = localStorage.getItem(storageKey);
    
    if (cachedItems) {
      try {
        const items = JSON.parse(cachedItems);
        const filteredItems = items.filter((item: RemediationItem) => item.id !== id);
        localStorage.setItem(storageKey, JSON.stringify(filteredItems));
      } catch (error) {
        console.error('Failed to update cached remediation items:', error);
      }
    }
    
    // 更新最近使用的计划ID
    updateRecentPlanId(planId);
    
    return true;
  } catch (error) {
    console.error(`Failed to delete remediation item ${id}:`, error);
    return false;
  }
};

/**
 * 切换整改项状态
 */
export const toggleRemediationStatus = async (item: RemediationItem): Promise<RemediationItem | null> => {
  try {
    // 准备状态更新数据
    const update_status = item.status == RemediationStatus.IN_PROGRESS ? RemediationStatus.COMPLETED : RemediationStatus.IN_PROGRESS;
    const statusUpdate = {
      status: update_status
    };
    
    // 使用专门的状态更新接口
    const updatedBackendItem = await typedHttp.patch<Record<string, any>, Record<string, any>>(
      `/remediation/${item.id}/status`, 
      statusUpdate
    );
    
    // 转换回前端格式
    const updatedItem = toFrontendFormat(updatedBackendItem);
    
    // 更新本地缓存
    if (item.plan_id) {
      try {
        const storageKey = `${STORAGE_KEY_PREFIX}${item.plan_id}`;
        const cachedItems = localStorage.getItem(storageKey);
        if (cachedItems) {
          const items = JSON.parse(cachedItems);
          const updatedItems = items.map((item: RemediationItem) => 
            item.id === updatedItem.id ? updatedItem : item
          );
          localStorage.setItem(storageKey, JSON.stringify(updatedItems));
        }
      } catch (error) {
        console.error('Failed to update cached remediation items:', error);
      }
    }
    
    // 更新最近使用的计划ID
    updateRecentPlanId(item.plan_id);
    
    return updatedItem;
  } catch (error) {
    console.error(`Failed to toggle status for remediation item ${item.id}:`, error);
    return null;
  }
};

/**
 * 将前端数据转换为后端API所需的格式
 * @param item 前端格式的整改项数据
 * @returns 转换为后端API格式的数据
 */
export const toBackendFormat = (item: RemediationItem | RemediationFormData | Partial<RemediationItem>): Record<string, any> => {
  // 创建基础对象
  const backendItem: Record<string, any> = {};
  
  // 只添加存在的字段
  if ('title' in item && item.title !== undefined) backendItem.title = item.title;
  if ('description' in item && item.description !== undefined) backendItem.description = item.description;
  if ('suggestion' in item && item.suggestion !== undefined) backendItem.suggestion = item.suggestion;
  if ('riskLevel' in item && item.riskLevel !== undefined) backendItem.risk_level = item.riskLevel;
  if ('plan_id' in item && item.plan_id !== undefined) backendItem.plan_id = item.plan_id;
  if ('item_id' in item && item.item_id !== undefined && item.item_id !== '') backendItem.item_id = item.item_id;
  if ('status' in item && item.status !== undefined) backendItem.status = item.status;
  if ('completionDate' in item && item.completionDate !== undefined) backendItem.completion_date = item.completionDate;
  
  return backendItem;
};

/**
 * 将后端API返回的数据转换为前端所需的格式
 * @param backendItem 后端API返回的整改项数据
 * @returns 转换为前端格式的数据
 */
export const toFrontendFormat = (backendItem: Record<string, any>): RemediationItem => {
  return {
    id: backendItem.id,
    item_id: backendItem.item_id,
    plan_id: backendItem.plan_id,
    title: backendItem.title,
    description: backendItem.description,
    suggestion: backendItem.suggestion,
    riskLevel: backendItem.risk_level, // 转换为camelCase
    createdAt: backendItem.created_at, // 转换为camelCase
    status: backendItem.status as RemediationStatus,
    completionDate: backendItem.completion_date, // 转换为camelCase
    updatedAt: backendItem.updated_at || new Date().toISOString(), // 转换为camelCase
  };
};

/**
 * 从检查项创建整改项表单数据
 */
export const createFromComplianceItem = (complianceItem: ComplianceItem, planId: string): RemediationFormData => {
  return {
    title: complianceItem.title,
    description: complianceItem.description || '',
    suggestion: complianceItem.inspector || '请根据检查项要求进行整改',
    riskLevel: complianceItem.risk_level || RiskLevel.MEDIUM,
    item_id: complianceItem.id,
    plan_id: planId,
  };
};
